#!/usr/bin/bash

export SCRIPT_NAME="crt_down_flow"
export APPS_ROOT=/Apps/euclid/KIWIS/${install.dir}
export APP_HOME=$APPS_ROOT/CRT-DOWN-FLOW
export APP_CLASS=euclid.kiwis.crt.flow.CRTDownFlow
export SAX_DRIVER=org.apache.xerces.parsers.SAXParser
export JAVA_HOME=/Soft/JDK/150_15
export PIDFILE="${APPS_ROOT}/run/${SCRIPT_NAME}.pid"
export LOGDIR=$APPS_ROOT/log/CRT-DOWN-FLOW

export CLASSPATH=$APP_HOME:$CLASSPATH
export CLASSPATH=$APP_HOME/config:$CLASSPATH

for JARFILE in $APP_HOME/bin/*; do
	export CLASSPATH=$CLASSPATH:$JARFILE
done;

for JARFILE in $APP_HOME/lib/*; do
	export CLASSPATH=$CLASSPATH:$JARFILE
done;

start()
{
	if [ -f $PIDFILE ]; then
		PID=`cat ${PIDFILE}`
		echo "${SCRIPT_NAME} is already running with pid ${PID}"
		echo "You should try '$0 restart'"
		exit 3
	else
	    echo "starting ${SCRIPT_NAME}"
		$JAVA_HOME/bin/java  -Xms32M -Xmx256M -cp $CLASSPATH -Dorg.xml.sax.driver=$SAX_DRIVER $APP_CLASS &> $LOGDIR/crt-down-flow-sysout.log 2>&1 &
		if [ ! -d $APPS_ROOT/run ]; then
			mkdir $APPS_ROOT/run
		fi
	    echo "$!" > $PIDFILE
	fi
}


stop()
{
	if [ -f $PIDFILE ]; then
		PID=`cat ${PIDFILE}`
		echo "Stopping process ${PID}"
		kill -s TERM $PID 2 &> /dev/null
		
		if [ $? -ne 0 ]; then
			echo "process ${PID} does not exist ..."
			echo "This means that the process was not running or has not been started using this script."
		fi
		echo "removing ${PIDFILE}"
    	/bin/rm -f $PIDFILE
	else
		echo "${PIDFILE} does not exist, process should not be running, or this file has been deleted."
		echo "This means that the process was not running or has not been started using this script."
	fi
}



status()
{
	echo -n "Looking for file ${PIDFILE} :              "
	if [ -f $PIDFILE ]; then
		echo "OK."
		PID=`cat ${PIDFILE}`
		echo -n "Looking for process ${PID} in ps :         "

		ps | grep "^${PID} *java$" &> /dev/null
		FOUND=$?
		if [ $? -ne 0 ]; then
			echo "KO."
			exit 4;
		fi
		echo "OK."
	else
		echo "KO."
		exit 2
	fi
	exit 0
}



case $1 in
	start)
        start
 		;;

	restart)
        echo "restarting ${SCRIPT_NAME}"
        stop
        start
        ;;

	stop)
		stop
		;;

	status)
		status
		;;
		
	*)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

